from xiaoyiwy.xiaoyi.config import *
import requests

db = mysql()  # 以后每次需要数据库连接就是用connection（）函数获取连接就好了

# 获取openid,sessionkey
def gain_openid(data):
    appID = data['id']  # 开发者关于微信小程序的appID
    appSecret = data['secret']  # 开发者关于微信小程序的appSecret
    code = data['code']  # 前端POST过来的微信临时登录凭证code
    req_params = {
        'appid': appID,
        'secret': appSecret,
        'js_code': code,
        'grant_type': 'authorization_code'
    }
    wx_login_api = 'https://api.weixin.qq.com/sns/jscode2session'
    response_data = requests.get(wx_login_api, params=req_params)  # 向API发起GET请求
    type = response_data.json()
    openid = type['openid']  # 得到用户关于当前小程序的OpenID
    session_key = type['session_key']  # 得到用户关于当前小程序的会话密钥session_key
    wx_data = {
        "openid": openid,
        "session_key": session_key
    }
    return wx_data

# 存储个人信息
def wxdata(data):
    sql = "select count(open_id) from wxuser where open_id='%s'" % (data['openid'])
    conn = db.connection()
    cursor = conn.cursor()
    cursor.execute(sql)
    conn.commit()
    a = cursor.fetchall()[0][0]
    if a < 1:
        # 将得到的OpenID添加到数据库得用户表
        sql1 = "INSERT INTO wxuser (open_id,session_key,name,portrait,gender,province,city,country) " \
              "VALUES ('%s','%s','%s','%s','%s','%s','%s','%s')" % (data['openid'], data['session_key'],data['nickName'],data['avatarUrl'],data['gender'],data['province'],data['city'],data['country'])
        try:
            cursor.execute(sql1)
            conn.commit()
        except:
            return "报错了"
        user_data = {
            "code": 1,
            "error": "",
            "name" : data['nickName'],
            "province": data['avatarUrl']
        }
        mysql_close(cursor, conn)
        return user_data
    else:
        sql = "select name,portrait from wxuser where open_id = '%s'" % data['openid']
        try:
            cursor.execute(sql)
            conn.commit()
            data_user = cursor.fetchall()
            name = data_user[0][0]
            portrait = data_user[0][1]
            user_data = {
                "code": 1,
                "error": "",
                "name": name,
                "portrait": portrait
            }
            return user_data
        except:
            return "报错了"
